﻿using MessagePack;

namespace MQTTEntity
{
    [MessagePackObject]
    public class Message<T>
    {
        [Key(0)]
        public int Code { get; set; }
        [Key(1)]
        public string Msg { get; set; }
        [Key(2)]
        public T Data { get; set; }
    }
    public class MessageBuilder<T>
    {
        private int _code;
        private string _msg;
        private T _data;
        public static MessageBuilder<T> Create()
        {
            return new MessageBuilder<T>();
        }

        public MessageBuilder<T> WithCode(int code)
        {
            _code = code;
            return this;
        }

        public MessageBuilder<T> WithMsg(string msg)
        {
            _msg = msg;
            return this;
        }

        public MessageBuilder<T> WithData(T data)
        {
            _data = data;
            return this;
        }

        public byte[] Build()
        {
            var message = new Message<T>
            {
                Code = _code,
                Msg = _msg,
                Data = _data
            };
            byte[] bytes = MessagePackSerializer.Serialize(message);
            return bytes;
        }
    }

    public class MessageParser
    {
        public static Message<T> Parse<T>(byte[] bytes)
        {
            var message = MessagePackSerializer.Deserialize<Message<T>>(bytes);
            return message;
        }
    }
}
